package com.zhang.yygh.hosp.listener;

import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderMqVo;

import com.rabbitmq.client.Channel;
import com.zhang.yygh.hosp.service.ScheduleService;
import com.zhang.yygh.mq.MqConst;
import com.zhang.yygh.mq.RabbitService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class OrderListener {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitService rabbitService;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(name = MqConst.QUEUE_ORDER,durable = "true"),
                    exchange = @Exchange(name = MqConst.EXCHANGE_DIRECT_ORDER),
                    key = MqConst.ROUTING_ORDER

            )
    })
    public void consume(OrderMqVo orderMqVo, Message message, Channel channel){

        if (orderMqVo.getAvailableNumber()!=null){
            String scheduleId = orderMqVo.getScheduleId();
            Schedule schedule = scheduleService.getScheduleInfoById(scheduleId);
            //schedule.setReservedNumber(orderMqVo.getReservedNumber());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            scheduleService.update(schedule);
        }else {
            String scheduleId = orderMqVo.getScheduleId();
            //根据排班id查询出原来的排班数据
            Schedule schedule=scheduleService.getScheduleInfoByScheduleId(scheduleId);
            schedule.setAvailableNumber(schedule.getAvailableNumber()+1);
            scheduleService.update(schedule);
        }


        //发送短信
        MsmVo msmVo = orderMqVo.getMsmVo();
        if(null != msmVo) {
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SMS, MqConst.ROUTING_SMS_ITEM, msmVo);
        }
    }
}
